package com.ljkj.cordial.chat.fragment;


import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.activity.ApplyFriendActivity;
import com.ljkj.cordial.chat.activity.ChatMainActivity;
import com.ljkj.cordial.chat.activity.LeaveGroupActivity;
import com.ljkj.cordial.chat.activity.RefuseFriendActivity;
import com.ljkj.cordial.chat.activity.SysNotifyActivity;
import com.ljkj.cordial.chat.adapter.NavNotifyAdapter;
import com.ljkj.cordial.chat.base.BaseFragment;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.dao.BusinessLeaveTableDao;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.notify.BusinessLeaveTable;
import com.ljkj.cordial.chat.dao.notify.SysNoticeTable;
import com.ljkj.cordial.chat.listener.OnItemRemoveListener;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.widget.ChatItemPop;
import com.nic.view.widget.CircleImageView;
import com.nic.view.widget.CommonPopupWindow;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class NavNotifyFragment extends BaseFragment {


    @BindView(R.id.listView)
    RecyclerView listView;
    @BindView(R.id.tv_empty)
    ImageView tvEmpty;
    @BindView(R.id.iv_avatar)
    CircleImageView ivAvatar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.ll_notice)
    LinearLayout llNotice;
    @BindView(R.id.v_notice)
    View vNotice;
    @BindView(R.id.v_tran)
    View vTran;

    Unbinder unbinder;
    NavNotifyAdapter notifyAdapter;
    private List<SysNoticeTable> sysList = new ArrayList<>();
    private List<BusinessLeaveTable> leaveList = new ArrayList<>();
    private OnItemRemoveListener mOnItemRemoveListener;

    public static NavNotifyFragment newInstance(OnItemRemoveListener listener) {
        NavNotifyFragment fragment = new NavNotifyFragment();
        fragment.mOnItemRemoveListener = listener;
        return fragment;
    }

    public NavNotifyFragment() {
        // Required empty public constructor
    }

    @Override
    public int getContentLayoutId() {
        return R.layout.fragment_nav_notify;
    }

    @Override
    public void initView(View rootView) {
        unbinder = ButterKnife.bind(this, rootView);
        notifyAdapter = new NavNotifyAdapter();
        listView.setHasFixedSize(true);
        listView.setLayoutManager(new LinearLayoutManager(getActivity()));
        ((SimpleItemAnimator) listView.getItemAnimator()).setSupportsChangeAnimations(false);
        listView.setAdapter(notifyAdapter);
        notifyAdapter.setOnNotifyItemClickListener((view, position, msg) -> {
            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Boolean>() {
                @Override
                public void onAction(Boolean obj) {
                    view.findViewById(R.id.tv_num).setVisibility(View.INVISIBLE);
                    EventBus.getDefault().post(MessageEvent.cerateUiRefresh(EventConstants.Action.NOTIFY_NUMBER_CHANGED));
                }

                @Override
                public Boolean onThreadAction() {
                    msg.setIsRead(1);
                    DbController.getInstance().getWrite().getBusinessLeaveTableDao().update(msg);
                    return null;
                }
            });
            int state = msg.getTargetStatus();
            switch (state) {
                case IMSContacts.MsgContentType.INVITE_TOURISTS://消息类型为5，INVITE_TOURISTS,群主邀请游客用户的消息
                case IMSContacts.MsgContentType.INVITE_REGISTERED://消息类型为6，INVITE_REGISTERED，群主邀请注册用户的消息
                case IMSContacts.MsgContentType.APPLY_TOURISTS://消息类型为9，APPLY_TOURISTS,游客用户申请入群的消息
                case IMSContacts.MsgContentType.APPLY_REGISTERED://消息类型为10，APPLY_REGISTERED，注册用户申请入群的消息
                case IMSContacts.MsgContentType.APPLY_FRIEND_TOURISTS://消息类型13，游客用户好友申请
                case IMSContacts.MsgContentType.APPLY_FRIEND_REGISTERED://消息类型14，注册用户好友申请
                    ApplyFriendActivity.jumpTo(activity, msg);
                    break;
                case IMSContacts.MsgContentType.INVITE_REFUSE_TOURISTS://消息类型为7，INVITE_REFUSE_TOURISTS,游客用户拒绝群主邀请的消息
                case IMSContacts.MsgContentType.INVITE_REFUSE_REGISTERED://消息类型为8，INVITE_REFUSE_REGISTERED,注册用户拒绝群主邀请的消息
                case IMSContacts.MsgContentType.APPLY_REFUSE_TOURISTS://消息类型为11，APPLY_REFUSE_TOURISTS,游客群主拒绝申请入群的消息
                case IMSContacts.MsgContentType.APPLY_REFUSE_REGISTERED://消息类型为12，APPLY_REFUSE_REGISTERED,注册群主拒绝申请入群的消息
                case IMSContacts.MsgContentType.APPLY_REFUSE_FRIEND_TOURISTS://消息类型15，游客用户好友申请拒绝
                case IMSContacts.MsgContentType.APPLY_REFUSE_FRIEND_REGISTERED://消息类型16，注册用户好友申请拒绝
                    RefuseFriendActivity.jumpTo(activity, msg);
                    break;
                case IMSContacts.MsgContentType.DELETE_GROUP_MEMBER:
                case IMSContacts.MsgContentType.EXIT_GROUP:
                case IMSContacts.MsgContentType.DISSOLVE_GROUP:
                    LeaveGroupActivity.jumpTo(activity, msg);
                    break;
            }
        });
//        listView.setEmptyView(tvEmpty);
        llNotice.setOnClickListener(v -> SysNotifyActivity.jumpTo(activity));
        notifyAdapter.setOnNotifyItemLongClickListener((view, position, msg) -> {
            ChatItemPop pop = new ChatItemPop(activity);
            pop.setData("删    除");
            pop.setOnItemClickListener((parent, view1, position1, id) -> {
                ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                    @Override
                    public void onAction(Object obj) {
                        if (mOnItemRemoveListener != null)
                            mOnItemRemoveListener.onItemRemove();
                    }

                    @Override
                    public Object onThreadAction() {
                        DbController.getInstance().getWrite().delete(msg);
                        return null;
                    }
                });
                notifyAdapter.remove(position);
                setEmptyV(sysList.isEmpty(), notifyAdapter.getItemCount() == 0);
//                queryOfflineData();
            });
            pop.getPopupWindow().setOnDismissListener(() -> vTran.setVisibility(View.GONE));
            pop.showBashOfAnchor(view, new CommonPopupWindow.LayoutGravity(CommonPopupWindow.LayoutGravity.ALIGN_ABOVE | CommonPopupWindow.LayoutGravity.CENTER_HORI), 0, 14);
            vTran.setVisibility(View.VISIBLE);
            vTran.setOnClickListener(v -> vTran.setVisibility(View.GONE));
        });
    }

//    public List<MessageTableBean> getTest() {
//        List<MessageTableBean> list = new ArrayList<>();
////        list.add(getMessageTableBean(Canstants.MSG_TYPE_NOTIFY_SYS, "系统升级维护"));
//        list.add(getMessageTableBean(Canstants.MSG_TYPE_NOTIFY_FRIEND, "申请加为好友"));
//        list.add(getMessageTableBean(Canstants.MSG_TYPE_NOTIFY_GROUP, "申请加入 交流群"));
//        list.add(getMessageTableBean(Canstants.MSG_TYPE_NOTIFY_FRIEND_PASS, "同意了你的好友申请"));
//        list.add(getMessageTableBean(Canstants.MSG_TYPE_NOTIFY_GROUP_PASS, "同意了你的入群申请"));
//        list.add(getMessageTableBean(Canstants.MSG_TYPE_NOTIFY_FRIEND_REFUSED, "拒绝了你的好友申请"));
//        list.add(getMessageTableBean(Canstants.MSG_TYPE_NOTIFY_GROUP_REFUSED, "拒绝了你的入群申请"));
//        return list;
//    }


    @Override
    public void onResume() {
        super.onResume();
        queryOfflineData();
    }

    private void setEmptyV(boolean isNoticeMsg, boolean isLeaveMsg) {
        if (isNoticeMsg) {
            llNotice.setVisibility(View.GONE);
            vNotice.setVisibility(View.GONE);
        } else {
            llNotice.setVisibility(View.VISIBLE);
            vNotice.setVisibility(View.VISIBLE);
        }
        if (isLeaveMsg && isNoticeMsg) {
            tvEmpty.setVisibility(View.VISIBLE);
        } else {
            tvEmpty.setVisibility(View.GONE);
        }
    }


    /**
     * 查询离线通知
     */
    public void queryOfflineData() {
        ObserverThread.create().onNextThread1(new ObserverThread.OnMulActionListener() {
            @Override
            public void onAction(Object... obj) {
                sysList = (List<SysNoticeTable>) obj[0];
                leaveList = (List<BusinessLeaveTable>) obj[1];
                if (sysList != null && !sysList.isEmpty()) {
                    SysNoticeTable lastN = sysList.get(sysList.size() - 1);
                    tvTitle.setText(lastN.getTitle());
                    tvContent.setText(lastN.getContent());
                    tvNum.setText("" + sysList.size());
                }
                notifyAdapter.setList(leaveList);
                if (activity instanceof ChatMainActivity) {
                    ChatMainActivity act = (ChatMainActivity) activity;
                    int levelUnReadCount = 0;
                    for (BusinessLeaveTable businessLeaveTable : leaveList) {
                        if (businessLeaveTable.getIsRead() == 0) levelUnReadCount++;
                    }
                    act.setNotifySum(sysList.size() + levelUnReadCount);
                }
                setEmptyV(sysList.isEmpty(), leaveList.isEmpty());
            }

            @Override
            public Object[] onThreadAction() {
                List<SysNoticeTable> sList = DbController.getInstance().getRead().getSysNoticeTableDao().queryBuilder().list();
                List<BusinessLeaveTable> eList = DbController.getInstance().getRead().getBusinessLeaveTableDao().queryBuilder().where(BusinessLeaveTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())).list();
                return new Object[]{sList, eList};
            }
        });


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
